package com.hfzy.ihk.web.linkcall.controller.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.hfzy.ihk.common.constants.GlobalStatic;
import com.hfzy.ihk.common.util.http.HttpClientUtils;
import com.hfzy.ihk.common.util.string.StringUtil;
import com.hfzy.ihk.common.web.WebResult;
import com.hfzy.ihk.facade.calldata.entity.CallHistoryText;
import com.hfzy.ihk.facade.calldata.service.EsOptRmiService;
import com.hfzy.ihk.facade.linkcall.entity.knowledge.KnowledgeBase;
import com.hfzy.ihk.facade.linkcall.entity.knowledge.QuestionBase;
import com.hfzy.ihk.facade.linkcall.vo.knowledgeBase.KnowledgeBaseVo;
import com.hfzy.ihk.web.linkcall.biz.CallDataBiz;
import com.hfzy.ihk.web.linkcall.biz.KnowledgeBase.KnowledgeBaseBiz;
import com.hfzy.ihk.web.linkcall.biz.KnowledgeBase.QuestionBaseBiz;
import com.hfzy.ihk.web.linkcall.support.DefaultResult;
import com.hfzy.ihk.web.linkcall.utils.IKSegmenterUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/** 小程序接口专用Controller
 * @Auther: Administrator
 * @Date: 2019/3/5 16:50
 * @Description:
 */
@Controller
@RequestMapping("/api/weChatApp")
public class WeChatAppController {

    Logger logger = LoggerFactory.getLogger(WeChatAppController.class);

    @Autowired
    KnowledgeBaseBiz knowledgeBaseBiz;

    @Value("${aiService.knowledgebase.analysis.singleCall.url}")
    public String singleCallUrl;

    @Autowired
    private QuestionBaseBiz questionBaseBiz;

    @Autowired
    private CallDataBiz callDataBiz;

    @Reference(version = "1.0.0")
    private EsOptRmiService esOptRmiService;

    /**
     * 功能描述: 接受提交上来的所有问题,然后自动分词,返回到前台
     *
     * @param: Map 有两个参数,一个keywords为当前页面已经存在的关键词,allQuestions为所有问法
     * @return:
     * @auther:oyc
     * @date: 2018/10/12
     */
    @RequestMapping("knowledgeBase/autoAnalysis")
    @ResponseBody
    public DefaultResult autoAnalysis(@RequestParam Map<String, String> params) {

        DefaultResult result = new DefaultResult();

        List<String> newKeywords = new ArrayList<>();

        try {
            //获取所有的问法
            String[] allQuestions = params.get("allQuestions").split("\n+");

            if (allQuestions != null && allQuestions.length > 0) {

                //用IK分词器分词
                newKeywords = IKSegmenterUtils.getInstance().getKeywords(allQuestions);

                String[] temp = params.get("keywords").split(",");

                if (temp != null && temp.length > 0) {

                    //获取已经添加的关键字
                    List<String> originalKeywords = Arrays.asList(temp);
                    //去重
                    newKeywords.removeAll(originalKeywords);
                }

            }
            result.setCode("1");
            result.setMsg("成功");
            Map<String, Object> resultList = new HashMap<>();
            resultList.put("total", newKeywords.size());
            resultList.put("keywords", newKeywords);
            result.setData(resultList);
        } catch (Exception e) {
            logger.error("自动分词出现错误,赶紧来看看");
            e.printStackTrace();
            result.setCode("0");
            result.setMsg("出现异常");

        }
        return result;
    }


    /**
     * 功能描述:根据所给参数查询(精确查询)
     *
     * @param: []
     * @return: java.util.List<com.hfzy.ihk.facade.linkcall.entity.knowledge.KnowledgeBase>
     * @auther:
     * @date: 2018/8/23
     */
    @RequestMapping("knowledgeBase/selectByField")
    @ResponseBody
    public WebResult selectByField(@RequestParam Map<String, String> params) {

        WebResult webResult = new WebResult();

        try {
            //调用biz层
            List<KnowledgeBase> list = knowledgeBaseBiz.searchKnowledgeBaseByField(params);
            if (StringUtil.isNotNull(list)){
                webResult.setTotal(list.size());
                webResult.setRecords(list);
            }
            webResult.setCode(GlobalStatic.CODE_1);
            webResult.setMsg(GlobalStatic.SUCCESS);

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("搜索knowledgeBase出错");
            webResult.setCode(GlobalStatic.CODE_0);
            webResult.setMsg(GlobalStatic.FAIL);
            webResult.setTotal(0);
        }

        return webResult;

    }


    /**
     * 保存新增知识库
     *
     * @param knowledgeBaseVo
     * @return
     */
    @PostMapping("knowledgeBase/insert")
    @ResponseBody
    public WebResult esInsert(KnowledgeBaseVo knowledgeBaseVo) {

//        return  WebResultUtils.getSuccessCharWebResult("",0,null);
        //调用biz业务层
        return knowledgeBaseBiz.esInsert(knowledgeBaseVo);

    }

    /**
     * 根据字段编辑更新
     *
     * @param knowledgeBaseVo
     * @return
     */
    @RequestMapping("knowledgeBase/update")
    @ResponseBody
    public WebResult esUpdate(KnowledgeBaseVo knowledgeBaseVo) {

        //调用biz业务层
        return knowledgeBaseBiz.esUpdate(knowledgeBaseVo);

    }


    /**
     * 搜索问题
     * @param params
     * @return
     */
    @RequestMapping("learningAnalysis/searchQuestionBase")
    @ResponseBody
    public WebResult searchQuestionBase(@RequestParam  Map<String,Object> params){

        WebResult webResult=new WebResult();

        try {

            List<QuestionBase> questionBases = questionBaseBiz.searchByParam(params);
            webResult.setTotal(questionBases.size());
            webResult.setRecords(questionBases);

            webResult.setCode(GlobalStatic.CODE_1);
            webResult.setMsg(GlobalStatic.SUCCESS);

        }catch (Exception e){

            e.printStackTrace();
            logger.error("搜索QuestionBase出错");
            webResult.setCode(GlobalStatic.CODE_0);
            webResult.setMsg(GlobalStatic.FAIL);

        }

        return  webResult;
    }

    /**
     *查詢未識別問題的通話記錄
     * @return
     */
    @RequestMapping("learningAnalysis/getCallHistoryTest")
    @ResponseBody
    public WebResult getCallHistoryTest(@RequestParam Map<String,Object> params){

        WebResult result=new WebResult();
        try {

            //List<CallHistoryText> callHistoryTexts = esOptRmiService.searchCallHistoryTextList(params);
            List<CallHistoryText> callHistoryTexts = callDataBiz.searchCallHistoryTextList(params);
            result.setCode(GlobalStatic.CODE_1);
            result.setMsg(GlobalStatic.SUCCESS);
            result.setTotal(callHistoryTexts.size());
            result.setRecords(callHistoryTexts);

        }catch (Exception e){
            e.printStackTrace();
            result.setTotal(0);
            result.setMsg(GlobalStatic.FAIL);
            result.setCode(GlobalStatic.CODE_0);
        }

        return result;
    }

    /**
     * 功能描述:根据Id删除questionBase
     *
     * @param: [id]
     * @return: com.hfzy.ihk.common.web.WebResult
     * @auther:
     * @date: 2018/8/16
     */
    @RequestMapping("learningAnalysis/deleteById")
    @ResponseBody
    public WebResult deleteById(String id) {

        WebResult result = questionBaseBiz.esDeleteById(id);

        return result;
    }

    /**
     * 检测问法在同一话术包是否已经存在
     *
     * @return
     */
    @RequestMapping("knowledgeBase/checkTheHowQuestion")
    @ResponseBody
    public WebResult checkTheHowQuestion(KnowledgeBaseVo knowledgeBaseVo) {

        WebResult webResult = new WebResult();

        try {
            List<String> existedHowAskQuestions = knowledgeBaseBiz.checkTheHowQuestion(knowledgeBaseVo);

            webResult.setCode(GlobalStatic.CODE_1);

            webResult.setTotal(existedHowAskQuestions.size());

            webResult.setMsg("查询已存在问法成功");

            webResult.setRecords(existedHowAskQuestions);
        } catch (Exception e) {

            logger.info("查询已存在问法失败", e);

            webResult.setCode(GlobalStatic.CODE_0);

            webResult.setTotal(0);

            webResult.setMsg("查询已存在问法失败");

        }

        return webResult;
    }

    /**返回当前话术包下所有关键词
     * @return
     */
    @RequestMapping("knowledgeBase/getAllwords")
    @ResponseBody
    public WebResult getAllwords(@RequestParam Map<String, String> params) {

        WebResult webResult = new WebResult();

        try {

            Set<String> allwords = knowledgeBaseBiz.getAllwords(params);

            webResult.setCode(GlobalStatic.CODE_1);
            webResult.setMsg("查询当前话术包下所有关键词成功");

            if (allwords!=null){
                webResult.setTotal(allwords.size());
                webResult.setParameter(allwords);
            }else {
                webResult.setTotal(0);
                webResult.setParameter(allwords);
            }

        } catch (Exception e) {

            webResult.setCode(GlobalStatic.CODE_0);
            webResult.setMsg("查询当前话术包下所有关键词失败");
            webResult.setTotal(0);
        }

        return webResult;
    }

    /**返回当前话术包下所有问法
     * @return
     */
    @RequestMapping("knowledgeBase/getAllHowQuestions")
    @ResponseBody
    public WebResult getAllHowQuestions(@RequestParam Map<String, String> params) {

        WebResult webResult = new WebResult();

        try {

            List<String> allHowQuestions = knowledgeBaseBiz.getAllHowQuestions(params);

            webResult.setCode(GlobalStatic.CODE_1);
            webResult.setMsg("查询当前话术包下所有问法成功");

            if (allHowQuestions!=null){
                webResult.setTotal(allHowQuestions.size());
                webResult.setParameter(allHowQuestions);
            }else {
                webResult.setTotal(0);
                webResult.setParameter(allHowQuestions);
            }

        } catch (Exception e) {

            webResult.setCode(GlobalStatic.CODE_0);
            webResult.setMsg("查询当前话术包下所有问法失败");
            webResult.setTotal(0);
        }

        return webResult;

    }


    @Deprecated
    @RequestMapping("knowledgeBase/aicall/{id}")
    @ResponseBody
    public WebResult aicall(@PathVariable String id) {
        WebResult webResult = new WebResult();
        try {

            String method = HttpClientUtils.getMethod(singleCallUrl+"/knowledgebase/" + id);
            //String method = HttpClientUtils.getMethod("http://172.16.8.172:9999/analysis/knowledgebase/" + id);

            webResult.setMsg("调用python接口成功");
            webResult.setCode(GlobalStatic.CODE_1);
            webResult.setParameter(method);
        } catch (Exception e) {

            webResult.setMsg("调用python接口失败");
            webResult.setCode(GlobalStatic.CODE_0);
            webResult.setParameter(null);

        }

        return webResult;
    }
}
